package models.dao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import models.Food;
import models.OrderItem;
import models.User;
import play.db.jpa.GenericModel.JPAQuery;

public class OrderDAO {

	public static OrderItem placeOrder(long user_id, long food_id) {
		OrderItem ret = null;
		User user = User.findById(user_id);
		Food food = Food.findById(food_id);
		if (user != null && food != null)
			ret = placeOrder(user, food);
		return ret;
	}
	
	public static OrderItem placeOrder(String user_name,String user_ip, long food_id) {
		OrderItem ret = null;
		User user = UserDAO.getOrCreateUser(user_name, user_ip);
		Food food = Food.findById(food_id);
		if (user != null && food != null)
			ret = placeOrder(user, food,user_ip);
		return ret;
	}
	
	public static OrderItem placeOrder(User user, Food food )
	{
		return placeOrder( user,  food, user.ip);
	}

	public static OrderItem placeOrder(User user, Food food,String user_ip) {
		OrderItem ret = null;

		ret = new OrderItem();
		ret.user = user;
		ret.food = food;
		ret.add_date = Calendar.getInstance(TimeZone.getTimeZone("GMT+8")).getTime();
		ret.ip	= user_ip;
		ret.save();
		return ret;
	}
	
	public static List<OrderItem> getTodayOrders()
	{
		Date today,tommorrow;
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		if(cal.get(Calendar.HOUR_OF_DAY)>=13)
		{
			cal.set(Calendar.HOUR_OF_DAY, 13);

		}
		else
		{
			cal.set(Calendar.HOUR_OF_DAY, 13);
			cal.add(Calendar.DATE, -1);
		}
		today = cal.getTime();
		cal.add (Calendar.DATE, 1);
		tommorrow = cal.getTime();
		
		JPAQuery query =  OrderItem.find("add_date >= ? and add_date < ?", today,tommorrow);
		
		return query.fetch();
	}
}
